const Model = require('../models/device-model')
const OrderModel = require('../models/order-model')
const ResponseModel = require('../models/response-model')

const sleep = require('../utils/common').sleep
const getDevice = require('../utils/device').getDevice

module.exports = {

    // 查询
    'get::/device/list': async function(ctx) {

        const params = ctx.request.query
        
        const whereBuilder = countQuery => {
            if (params.keyword) {
                countQuery.where('name', 'like', `%${params.keyword}%`)
            }
        }

        const list = await Model.list(Model.buildPaging(params), whereBuilder)

        ctx.response.body = ResponseModel.success(list)
    },
    // 保存
    'post::/device/save': async function(ctx) {

        const model = ctx.request.body
        let id = model.id
        delete model.id
        
        let oldModel
        if (id) {
            oldModel = await Model.getById(id)
            const updated = await Model.updateBy(model, { id: id })
            model.id = id
        } else {
            const inserted = await Model.insert(model)
            if (inserted && inserted.length > 0) {
                id = inserted[0]
                model.id = inserted[0]
            }
        }

        ctx.response.body = ResponseModel.success()
    },
    // 删除
    'get::/device/delete/:id': async function(ctx) {

        const { id } = ctx.request.params
        if (id) {
            const deleted = await Model.delete({ id: id })
        }
        ctx.response.body = ResponseModel.success()
    },
    // 选项
    'get::/device/options': async function(ctx) {

        const params = ctx.request.query

        const list = await Model.list(Model.buildPaging({}))
        console.log('/device/options', list);
        ctx.response.body = ResponseModel.success(list.map(d => {
            return {
                ssid: d.ssid,
                id: d.id
            }
        }))
    },

    // --- 设备对接 ---
    // 握手
    'get::/device/check': async function(ctx) {

        const { id } = ctx.request.query
        
        let message = ''
        if(id) {
            const model = await Model.getById(id)
            if (model.ssid) {
                const device = getDevice(model)
                device.shakeHand()
                await sleep(1000)   
                message = device.lastResponse.message
            }
        }

        ctx.response.body = ResponseModel.success(null, message)
    },

    
}
  